package com.jinly.ryder.account.web;

import com.jinly.ryder.account.config.AuthProperties;
import com.jinly.ryder.account.web.utils.TokenUtil;
import com.jinly.ryder.common.auth.LoginContent;
import com.jinly.ryder.common.auth.model.TokenInfo;
import com.jinly.ryder.common.error.SystemErrorType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private AuthProperties authProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            if (HttpMethod.OPTIONS.matches(request.getMethod())) return true;
            TokenInfo token = TokenUtil.parseToken(request, authProperties).orElseThrow(() -> SystemErrorType.UNAUTHORIZED.buildError());
            LoginContent.setContent(token);
        }
        return true;
    }
}
